package cn.aishua.ui.main;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;
import cn.aishua.R;
import cn.aishua.data.DataProvider;
import cn.aishua.data.HotsDataParser;
import cn.aishua.data.HotsDataParser.HotsVendor;
import cn.aishua.data.PostsDataParser;
import cn.aishua.data.PostsDataParser.PostsVendor;
import cn.aishua.data.ResourceDataParser;
import cn.aishua.data.ResourceDataParser.Item;
import cn.aishua.location.Locator;
import cn.aishua.network.HttpRequestUtil;
import cn.aishua.ui.MainActivityGroup;
import cn.aishua.ui.vendor.VendorDetailActivity;
import cn.aishua.util.Constant;
import cn.aishua.util.FormatConverter;
import cn.aishua.util.ImageLoader;
import cn.aishua.util.Utils;

import com.baidu.location.BDLocation;

public class HotsActivity
    extends Activity
{

    //    TextView textHeaderTitle;
    //    ImageView imageFunc;

    RelativeLayout linearPics;
    LinearLayout linearFood;
    LinearLayout linearEntertain;
    LinearLayout linearShop;
    LinearLayout linearLife;
    LinearLayout linearTravel;
    TextView textFooterMsg;
    ProgressBar progressBar1;

    RelativeLayout linearWall;
    ImageView imagePostCener;
    LinearLayout linearInfo;
    TextView textRate;
    TextView textName;
    TextView textAvgPrice;
    TextView textDistance;
    TextView textTag;
    TextView textSubCat;
    TextView textBusinessCir;
    TextView textFooterPostMsg;

    static final int MSG_FETCH_DONE = 100;
    static final int MSG_DOWNLOAD_IMAGE_DONE = 200;
    static final int MSG_FETCH_POST_DONE = 300;

    HotsDataParser mData;
    PostsDataParser mPdata = null;

    String testLink = // "http://hiphotos.baidu.com/pochacco_pp/pic/item/b10f840192014847728da500.jpg";
    "http://c.hiphotos.baidu.com/album/s%3D740%3Bq%3D90/sign=9470989c7cd98d1072d40e351104c933/4afbfbedab64034fc25dcc66afc379310a551d39.jpg";

    String testPLink = "http://h.hiphotos.baidu.com/album/s%3D740%3Bq%3D90/sign=56fdb7cca044ad342abf8583e0997dc9/9f510fb30f2442a71eede884d043ad4bd113022b.jpg";

    List<Item> vendorTypes = new ArrayList<Item>();

    private ViewFlipper vfRecomm;
    private ViewFlipper vfPoster;

    private int recommPage = 1;// current page 
    private int posterPage = 1;// current page

    //    private GestureDetector detector;
    boolean hasInitPoster = false;

    private Map<String, ImageView> imageMap = new HashMap<String, ImageView>(); // check whether the bitmap has been recycled

    // page header widgets
    private ImageView ivLeftBtn;
    private ImageView ivRightBtn;
    private TextView tvTitile;

    private void initPageHeader()
    {
        // left button
        ivLeftBtn = (ImageView) findViewById( R.id.page_header_iv_left_btn );
        ivLeftBtn.setImageResource( R.drawable.btn_nav_header );
        ivLeftBtn.setOnClickListener( new View.OnClickListener()
        {

            @Override
            public void onClick( View v )
            {
                navigationBar( v );
            }
        } );

        // title
        tvTitile = (TextView) findViewById( R.id.page_header_tv_title );
        tvTitile.setText( "首页" );

        // right button
        ivRightBtn = (ImageView) findViewById( R.id.page_header_iv_right_btn );
        ivRightBtn.setImageResource( R.drawable.btn_func_wall );
        ivRightBtn.setOnClickListener( imageFuncClickListener );
    }

    @Override
    protected void onCreate( Bundle savedInstanceState )
    {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.hots );
        initPageHeader();
        init();
    }

    @Override
    protected void onResume()
    {
        super.onResume();
    }

    @Override
    protected void onNewIntent( Intent intent )
    {
        super.onNewIntent( intent );

        // reload image
        Set<Entry<String, ImageView>> entries = imageMap.entrySet();
        Iterator<Entry<String, ImageView>> iter = entries.iterator();
        while( iter.hasNext() )
        {
            Entry<String, ImageView> entry = iter.next();
            ImageLoader.getInstance( this ).loadImage( entry.getKey(), entry.getValue() );
        }

        if( intent.getBooleanExtra( "isPoster", false ) )
        {
            if( hasInitPoster )
            {
                ivRightBtn.setImageResource( R.drawable.btn_func_pics );
                tvTitile.setText( "热门推荐" );
                linearPics.setVisibility( View.GONE );
                linearWall.setVisibility( View.VISIBLE );
                STATE = STATE_WALL;
            }
            else
            {
                showPoster();
                hasInitPoster = true;
            }
        }
        else
        {
            ivRightBtn.setImageResource( R.drawable.btn_func_wall );
            tvTitile.setText( "首页" );
            linearPics.setVisibility( View.VISIBLE );
            linearWall.setVisibility( View.GONE );
            STATE = STATE_PICS;
            //            initRecomm();
            //            show( nowIndex );
        }
    }

    private void init()
    {
        getVendorTypes();

        //        textHeaderTitle = (TextView) findViewById( R.id.textHeaderTitle );
        //        imageFunc = (ImageView) findViewById( R.id.imageFunc );
        vfRecomm = (ViewFlipper) findViewById( R.id.hots_vf_recomm );
        vfPoster = (ViewFlipper) findViewById( R.id.hots_vf_poster );
        //        detector = new GestureDetector( this );

        linearPics = (RelativeLayout) findViewById( R.id.linearPics );

        linearFood = (LinearLayout) findViewById( R.id.linearFood );
        linearEntertain = (LinearLayout) findViewById( R.id.linearEntertain );
        linearShop = (LinearLayout) findViewById( R.id.linearShop );
        linearLife = (LinearLayout) findViewById( R.id.linearLife );
        linearTravel = (LinearLayout) findViewById( R.id.linearTravel );
        nowIndex = 0;
        //        linearFood.setVisibility( View.GONE );
        //        linearEntertain.setVisibility( View.GONE );
        //        linearShop.setVisibility( View.GONE );
        //        linearLife.setVisibility( View.GONE );
        //        linearTravel.setVisibility( View.GONE );
        linearFood.setOnTouchListener( commonTouchListener );
        linearFood.setOnClickListener( dummyClickListener );
        linearEntertain.setOnTouchListener( commonTouchListener );
        linearEntertain.setOnClickListener( dummyClickListener );
        linearShop.setOnTouchListener( commonTouchListener );
        linearShop.setOnClickListener( dummyClickListener );
        linearLife.setOnTouchListener( commonTouchListener );
        linearLife.setOnClickListener( dummyClickListener );
        linearTravel.setOnTouchListener( commonTouchListener );
        linearTravel.setOnClickListener( dummyClickListener );

        vs[0] = linearFood;
        vs[1] = linearEntertain;
        vs[2] = linearShop;
        vs[3] = linearLife;
        vs[4] = linearTravel;
        //        imageFunc.setOnClickListener( imageFuncClickListener );

        textFooterMsg = (TextView) findViewById( R.id.textFooterMsg );
        progressBar1 = (ProgressBar) findViewById( R.id.progressBar1 );
        progressBar1.setVisibility( View.GONE );

        linearWall = (RelativeLayout) findViewById( R.id.linearWall );
        linearWall.setVisibility( View.GONE );

        //        linearInfo = (LinearLayout) findViewById( R.id.linearInfo );

        textRate = (TextView) findViewById( R.id.textRate );
        textName = (TextView) findViewById( R.id.textName );
        textAvgPrice = (TextView) findViewById( R.id.textAvgPrice );
        textDistance = (TextView) findViewById( R.id.textDistance );
        textTag = (TextView) findViewById( R.id.textTag );
        textSubCat = (TextView) findViewById( R.id.textSubCat );
        textBusinessCir = (TextView) findViewById( R.id.textBusinessCir );
        textFooterPostMsg = (TextView) findViewById( R.id.textFooterPostMsg );

        //        imagePostCener.setOnTouchListener( commonTouchListener );
        //        linearInfo.setOnTouchListener( commonTouchListener );
        //        linearInfo.setOnClickListener( dummyClickListener );

        STATE = STATE_PICS;
        linearPics.setVisibility( View.VISIBLE );
        linearWall.setVisibility( View.GONE );

        //        if( getIntent().getBooleanExtra( "isPoster", false ) )
        //        {
        //            showPoster();
        //        }
        //        else
        //        {
        fetch();
        //        }
    }

    private void getVendorTypes()
    {
        ResourceDataParser parser = new ResourceDataParser( Constant.RESOURCE );
        for( Map.Entry<Item, Map<Integer, Item>> entry : parser.category.entrySet() )
        {
            if( entry.getKey().id != 0 ) // exclude type (all vendor)
            {
                vendorTypes.add( entry.getKey() );
            }
        }
    }

    static final int STATE_PICS = 0;
    static final int STATE_WALL = 1;
    private int STATE = -1;

    private OnClickListener imageFuncClickListener = new OnClickListener()
    {
        public void onClick( View v )
        {
            MainActivityGroup parent = (MainActivityGroup) HotsActivity.this.getParent();
            parent.ignoreNaviBar = true;

            switch( STATE )
            {
                case STATE_PICS:
                    parent.switchActivityForFixTabs( 1 );
                    //                    showPoster();
                    break;
                case STATE_WALL:
                    parent.switchActivityForFixTabs( 0 );
                    //                    ivRightBtn.setImageResource( R.drawable.btn_func_wall );
                    //                    tvTitile.setText( "爱刷优惠" );
                    //                    linearPics.setVisibility( View.VISIBLE );
                    //                    linearWall.setVisibility( View.GONE );
                    //                    STATE = STATE_PICS;
                    //                    initRecomm();
                    //                    show( nowIndex );
                    break;
            }

        }

    };

    private void showPoster()
    {
        ivRightBtn.setImageResource( R.drawable.btn_func_pics );
        tvTitile.setText( "热门推荐" );
        linearPics.setVisibility( View.GONE );
        STATE = STATE_WALL;

        if( mPdata == null )
        {
            // first time to wall
            fetchPost();
        }
        else
        {
            linearWall.setVisibility( View.VISIBLE );
            initPoster();
            //                        showPost( nowPostIndex );
        }
    }

    Thread fetchThread = new Thread()
    {
        public void run()
        {
            try
            {
                MainActivityGroup main = (MainActivityGroup) HotsActivity.this.getParent();
                while( main.clickArea.getVisibility() != View.GONE )
                {

                }
                HttpResponse response = HttpRequestUtil.getInstance().getHomeVendors();
                mData = new HotsDataParser( getData( response ) );
                mHandler.obtainMessage( MSG_FETCH_DONE ).sendToTarget();
            }
            catch( Exception e )
            {
                e.printStackTrace();
            }
        }
    };

    Thread fetchPostThread = new Thread()
    {
        public void run()
        {
            try
            {
                BDLocation location = Locator.getInstance( null ).getLocation();
                String x = "" + location.getLatitude();
                String y = "" + location.getLongitude();

                MainActivityGroup main = (MainActivityGroup) HotsActivity.this.getParent();
                while( main.clickArea.getVisibility() != View.GONE )
                {

                }

                HttpResponse response = HttpRequestUtil.getInstance().getRecommandVendors( x, y );
                mPdata = new PostsDataParser( getData( response ) );
                mHandler.obtainMessage( MSG_FETCH_POST_DONE ).sendToTarget();
            }
            catch( Exception e )
            {
                e.printStackTrace();
            }
        }
    };

    Handler mHandler = new Handler()
    {
        public void handleMessage( android.os.Message msg )
        {
            switch( msg.what )
            {
                case MSG_FETCH_DONE:
                    progressBar1.setVisibility( View.GONE );
                    ivRightBtn.setEnabled( true );
                    // bindData();
                    //                    show( nowIndex );
                    initRecomm();
                    break;
                case MSG_DOWNLOAD_IMAGE_DONE:
                    Object[] objs = (Object[]) msg.obj;
                    WeakReference<Bitmap> wfBitmap = new WeakReference<Bitmap>( (Bitmap) objs[1] );
                    ( (ImageView) objs[0] ).setImageBitmap( wfBitmap.get() );
                    wfBitmap = null;
                    //                    trashBin.add( new Object[] { (ImageView) objs[0], (Bitmap) objs[1] } );
                    break;
                case MSG_FETCH_POST_DONE:
                    progressBar1.setVisibility( View.GONE );
                    ivRightBtn.setEnabled( true );

                    linearWall.setVisibility( View.VISIBLE );
                    //                    showPost( nowPostIndex );
                    initPoster();
                    break;
            }
        }

    };

    private void initRecomm()
    {
        //        for( int i = 0; i < trashBin.size(); i++ )
        //        {
        //            Object[] objs = trashBin.get( i );
        //            ( (ImageView) objs[0] ).setImageResource( R.drawable.member_pic );
        //            ( (Bitmap) objs[1] ).recycle();
        //        }
        //        trashBin.clear();

        bindFood();
        bindEntertain();
        bindShop();
        bindLife();
        bindTravel();
        //        textFooterMsg.setText( ( index + 1 ) + "/5" );
        //        vs[index].setVisibility( View.VISIBLE );
    }

    protected void initPoster()
    {

        //        for( int i = 0; i < trashBin.size(); i++ )
        //        {
        //            Object[] objs = trashBin.get( i );
        //            ( (ImageView) objs[0] ).setImageResource( R.drawable.member_pic );
        //            ( (Bitmap) objs[1] ).recycle();
        //        }

        for( int index = 0; index < mPdata.data.size(); index++ )
        {
            View posterItem = LayoutInflater.from( this ).inflate( R.layout.poster_item, null );

            textRate = (TextView) posterItem.findViewById( R.id.textRate );
            textName = (TextView) posterItem.findViewById( R.id.textName );
            textAvgPrice = (TextView) posterItem.findViewById( R.id.textAvgPrice );
            textDistance = (TextView) posterItem.findViewById( R.id.textDistance );
            textTag = (TextView) posterItem.findViewById( R.id.textTag );
            textSubCat = (TextView) posterItem.findViewById( R.id.textSubCat );
            textBusinessCir = (TextView) posterItem.findViewById( R.id.textBusinessCir );
            imagePostCener = (ImageView) posterItem.findViewById( R.id.imagePostCener );
            linearInfo = (LinearLayout) posterItem.findViewById( R.id.linearInfo );

            final PostsVendor obj = mPdata.data.get( index );
            textRate.setText( (int) ( obj.max_customer_rate * 100 ) + "%" );
            textName.setText( obj.name );
            textAvgPrice.setText( "人均:￥" + (int) obj.average_price );
            //        textDistance.setText( "距离:" + Utils.doDistance( obj.distance ) );
            Log.d( "HotsActivity", "distance: " + obj.distance );
            textDistance.setText( "距离:" + getDistance( obj.lati, obj.longt ) );

            textTag.setText( "" );
            textSubCat.setText( "" );
            textBusinessCir.setText( "" );

            View[] views = new View[] { textTag, textSubCat, textBusinessCir };
            int j = 0;
            for( int i = 0; i < obj.merchant_tags.size(); i++ )
            {
                if( obj.merchant_tags.get( i ).type.equals( "business" ) )
                {
                    ( (TextView) views[j] ).setText( obj.merchant_tags.get( i ).name );
                    j++;
                }
            }

            textFooterPostMsg.setText( posterPage + "/" + mPdata.count );
            //            boolean downloadPicUnder2G3G = getSharedPreferences( "setting", Context.MODE_PRIVATE ).getBoolean(
            //                SharedPrefConst.SHARED_PREF_BOOL_DONW_PIC_UNDER_2G3G, false );
            //
            //            if( downloadPicUnder2G3G || NetworkState.isWifiAvailable( getApplicationContext() ) )
            //            {
            //                //                new DownloadPicTask( this, imagePostCener ).execute( obj.file_url );
            ImageLoader.getInstance( HotsActivity.this ).loadImage( obj.file_url, imagePostCener );
            imageMap.put( obj.file_url, imagePostCener );
            //            }

            //            byte[] temp = null;
            //            if( ( temp = DataProvider.getInstance( HotsActivity.this ).tryGetTempPic( obj.id ) ) != null )
            //            {
            //                // reuse pic from database
            //
            //                try
            //                {
            //                    Bitmap tempBitmap = BitmapFactory.decodeByteArray( temp, 0, temp.length );
            //                    WeakReference<Bitmap> wfBitmap = new WeakReference<Bitmap>( tempBitmap );
            //                    imagePostCener.setImageBitmap( wfBitmap.get() );
            //                    tempBitmap = null;
            //                }
            //                catch( OutOfMemoryError e )
            //                {
            //                    Log.e( "HotsActivity", e.getMessage() );
            //                }
            //            }
            //            else
            //            {
            //                boolean downloadPicUnder2G3G = getSharedPreferences( "setting", Context.MODE_PRIVATE ).getBoolean(
            //                    SharedPrefConst.SHARED_PREF_BOOL_DONW_PIC_UNDER_2G3G, false );
            //
            //                if( downloadPicUnder2G3G || NetworkState.isWifiAvailable( getApplicationContext() ) )
            //                {
            //                    //                    downloadImage( imagePostCener, obj.file_url, obj.id );
            //                    new DownloadPicTask( this, imagePostCener ).execute( obj.file_url );
            //                }
            //            }

            imagePostCener.setOnTouchListener( commonTouchListener );
            linearInfo.setOnTouchListener( commonTouchListener );
            linearInfo.setOnClickListener( dummyClickListener );

            imagePostCener.setOnClickListener( new OnClickListener()
            {
                public void onClick( View v )
                {
                    // TODO with the id (obj.id)
                    if( !shouldPerformClick )
                        return;
                    l( "post clicked " + obj.id );
                    toVendorDetail( obj.id );
                }
            } );

            vfPoster.addView( posterItem );
        }

    }

    private String getData( HttpResponse response )
    {
        int statusCode = response.getStatusLine().getStatusCode();
        l( "getData statusCode " + statusCode );
        if( HttpStatus.SC_OK == statusCode )
        {
            try
            {
                HttpEntity entity = response.getEntity();
                String s;
                s = EntityUtils.toString( entity );
                l( "getData with s " + s );
                return s;
            }
            catch( Exception e )
            {
                Log.e( "test", e.getMessage() );
                return "";
            }
        }
        return "";
    }

    private void goToVendorList( int index )
    {

        MainActivityGroup parent = (MainActivityGroup) getParent();
        parent.ignoreNaviBar = true;
        parent.switchActivityForDynTabs( index );
        //        parent.getTabHost().setCurrentTabByTag( "" + index );
        //        parent.ignoreNaviBar = false;

        //        Intent intent = new Intent( this, MainActivity.class );
        //        intent.addFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP );
        //        intent.putExtra( Constant.EXTRA_INT_CRITERIA_PARE_CATE, index );
        //        intent.putExtra( Constant.EXTRA_INT_CRITERIA_SUB_CATE, 0 );
        //        intent.putExtra( Constant.EXTRA_INT_CRITERIA_CANTON, 0 );
        //        intent.putExtra( Constant.EXTRA_INT_CRITERIA_BUSI_CIRC, 0 );
        //
        //        intent.putExtra( MainActivity.TAB, "" + index );
        //        startActivity( intent );
        //        //finish();
    }

    private void bindFood()
    {
        ArrayList<HotsVendor> data = mData.cuisineVendors;

        View v1 = linearFood.findViewById( R.id.item1 );
        View v2 = linearFood.findViewById( R.id.item2 );
        View v3 = linearFood.findViewById( R.id.item3 );

        View.OnClickListener listener = new OnClickListener()
        {
            public void onClick( View v )
            {
                if( !shouldPerformClick )
                    return;
                //                goToVendorList( vendorTypes.get( 0 ).id );
                goToVendorList( 0 );
            }
        };

        ( (TextView) v2.findViewById( R.id.textView2 ) ).setText( vendorTypes.get( 0 ).name );
        ( (TextView) v2.findViewById( R.id.textView2 ) ).setBackgroundColor( Color.parseColor( "#f3a448" ) );
        ( (TextView) v2.findViewById( R.id.textView2 ) ).setOnTouchListener( commonTouchListener );
        ( (TextView) v2.findViewById( R.id.textView2 ) ).setOnClickListener( listener );

        ( (TextView) v2.findViewById( R.id.textView3 ) ).setText( "共" + mData.cuisineCategoryStoresCount + "家商户" );
        ( (TextView) v2.findViewById( R.id.textView3 ) ).setBackgroundColor( Color.parseColor( "#f3a448" ) );
        ( (TextView) v2.findViewById( R.id.textView3 ) ).setOnTouchListener( commonTouchListener );
        ( (TextView) v2.findViewById( R.id.textView3 ) ).setOnClickListener( listener );

        bindCommon( data, v1, v2, v3 );
    }

    private void bindEntertain()
    {
        ArrayList<HotsVendor> data = mData.entertainmentVendors;
        View v1 = linearEntertain.findViewById( R.id.item1 );
        View v2 = linearEntertain.findViewById( R.id.item2 );
        View v3 = linearEntertain.findViewById( R.id.item3 );

        View.OnClickListener listener = new OnClickListener()
        {
            public void onClick( View v )
            {
                if( !shouldPerformClick )
                    return;
                goToVendorList( 1 );
            }
        };

        ( (TextView) v2.findViewById( R.id.textView2 ) ).setText( vendorTypes.get( 1 ).name );
        ( (TextView) v2.findViewById( R.id.textView2 ) ).setBackgroundColor( Color.parseColor( "#f37f62" ) );
        ( (TextView) v2.findViewById( R.id.textView2 ) ).setOnTouchListener( commonTouchListener );
        ( (TextView) v2.findViewById( R.id.textView2 ) ).setOnClickListener( listener );

        ( (TextView) v2.findViewById( R.id.textView3 ) ).setText( "共" + mData.entertainmentCategoryStoresCount + "家商户" );
        ( (TextView) v2.findViewById( R.id.textView3 ) ).setBackgroundColor( Color.parseColor( "#f37f62" ) );
        ( (TextView) v2.findViewById( R.id.textView3 ) ).setOnTouchListener( commonTouchListener );
        ( (TextView) v2.findViewById( R.id.textView3 ) ).setOnClickListener( listener );

        bindCommon( data, v1, v2, v3 );
    }

    private void bindShop()
    {
        ArrayList<HotsVendor> data = mData.marketVendors;
        View v1 = linearShop.findViewById( R.id.item1 );
        View v2 = linearShop.findViewById( R.id.item2 );
        View v3 = linearShop.findViewById( R.id.item3 );

        View.OnClickListener listener = new OnClickListener()
        {
            public void onClick( View v )
            {
                if( !shouldPerformClick )
                    return;
                goToVendorList( 2 );
            }
        };

        ( (TextView) v2.findViewById( R.id.textView2 ) ).setText( vendorTypes.get( 2 ).name );
        ( (TextView) v2.findViewById( R.id.textView2 ) ).setBackgroundColor( Color.parseColor( "#e274a5" ) );
        ( (TextView) v2.findViewById( R.id.textView2 ) ).setOnTouchListener( commonTouchListener );
        //        ( (TextView) v2.findViewById( R.id.textView2 ) ).setOnClickListener( listener );

        ( (TextView) v2.findViewById( R.id.textView3 ) ).setText( "共" + mData.marketCategoryStoresCount + "家商户" );
        ( (TextView) v2.findViewById( R.id.textView3 ) ).setBackgroundColor( Color.parseColor( "#e274a5" ) );
        ( (TextView) v2.findViewById( R.id.textView3 ) ).setOnTouchListener( commonTouchListener );
        ( (TextView) v2.findViewById( R.id.textView3 ) ).setOnClickListener( listener );

        bindCommon( data, v1, v2, v3 );
    }

    private void bindLife()
    {
        ArrayList<HotsVendor> data = mData.lifeVendors;
        View v1 = linearLife.findViewById( R.id.item1 );
        View v2 = linearLife.findViewById( R.id.item2 );
        View v3 = linearLife.findViewById( R.id.item3 );

        View.OnClickListener listener = new OnClickListener()
        {
            public void onClick( View v )
            {
                if( !shouldPerformClick )
                    return;
                goToVendorList( 3 );
            }
        };

        ( (TextView) v2.findViewById( R.id.textView2 ) ).setText( vendorTypes.get( 3 ).name );
        ( (TextView) v2.findViewById( R.id.textView2 ) ).setBackgroundColor( Color.parseColor( "#67b3d3" ) );
        ( (TextView) v2.findViewById( R.id.textView2 ) ).setOnTouchListener( commonTouchListener );
        ( (TextView) v2.findViewById( R.id.textView2 ) ).setOnClickListener( listener );

        ( (TextView) v2.findViewById( R.id.textView3 ) ).setText( "共" + mData.lifeCategoryStoresCount + "家商户" );
        ( (TextView) v2.findViewById( R.id.textView3 ) ).setBackgroundColor( Color.parseColor( "#67b3d3" ) );
        ( (TextView) v2.findViewById( R.id.textView3 ) ).setOnTouchListener( commonTouchListener );
        ( (TextView) v2.findViewById( R.id.textView3 ) ).setOnClickListener( listener );

        bindCommon( data, v1, v2, v3 );
    }

    private void bindTravel()
    {
        ArrayList<HotsVendor> data = mData.hotelVendors;
        View v1 = linearTravel.findViewById( R.id.item1 );
        View v2 = linearTravel.findViewById( R.id.item2 );
        View v3 = linearTravel.findViewById( R.id.item3 );

        View.OnClickListener listener = new OnClickListener()
        {
            public void onClick( View v )
            {
                if( !shouldPerformClick )
                    return;
                goToVendorList( 4 );
            }
        };

        ( (TextView) v2.findViewById( R.id.textView2 ) ).setText( vendorTypes.get( 4 ).name );
        ( (TextView) v2.findViewById( R.id.textView2 ) ).setBackgroundColor( Color.parseColor( "#8bc763" ) );
        ( (TextView) v2.findViewById( R.id.textView2 ) ).setOnTouchListener( commonTouchListener );
        ( (TextView) v2.findViewById( R.id.textView2 ) ).setOnClickListener( listener );

        ( (TextView) v2.findViewById( R.id.textView3 ) ).setText( "共" + mData.hotelCategoryStoresCount + "家商户" );
        ( (TextView) v2.findViewById( R.id.textView3 ) ).setBackgroundColor( Color.parseColor( "#8bc763" ) );
        ( (TextView) v2.findViewById( R.id.textView3 ) ).setOnTouchListener( commonTouchListener );
        ( (TextView) v2.findViewById( R.id.textView3 ) ).setOnClickListener( listener );

        bindCommon( data, v1, v2, v3 );
    }

    private void bindCommon( ArrayList<HotsVendor> data, View v1, View v2, View v3 )
    {

        for( int i = 0; i < data.size(); i++ )
        {
            switch( i )
            {
                case 0:
                    bindItem( data.get( 0 ), (ImageView) v1.findViewById( R.id.imageView1 ),
                        (TextView) v1.findViewById( R.id.textView1 ) );
                    break;
                case 1:
                    bindItem( data.get( 1 ), (ImageView) v1.findViewById( R.id.imageView2 ),
                        (TextView) v1.findViewById( R.id.textView2 ) );
                    break;
                case 2:
                    bindItem( data.get( 2 ), (ImageView) v1.findViewById( R.id.imageView3 ),
                        (TextView) v1.findViewById( R.id.textView3 ) );
                    break;
                case 3:
                    bindItem( data.get( 3 ), (ImageView) v2.findViewById( R.id.imageView1 ),
                        (TextView) v2.findViewById( R.id.textView1 ) );
                    break;
                case 4:
                    bindItem( data.get( 4 ), (ImageView) v3.findViewById( R.id.imageView1 ),
                        (TextView) v3.findViewById( R.id.textView1 ) );
                    break;
                case 5:
                    bindItem( data.get( 5 ), (ImageView) v3.findViewById( R.id.imageView2 ),
                        (TextView) v3.findViewById( R.id.textView2 ) );
                    break;
                case 6:
                    bindItem( data.get( 6 ), (ImageView) v3.findViewById( R.id.imageView3 ),
                        (TextView) v3.findViewById( R.id.textView3 ) );
                    break;
            }
        }
    }

    private void bindItem( final HotsVendor o, ImageView iv, TextView tv )
    {
        setText( tv, o.name );

        //        boolean downloadPicUnder2G3G = getSharedPreferences( "setting", Context.MODE_PRIVATE ).getBoolean(
        //            SharedPrefConst.SHARED_PREF_BOOL_DONW_PIC_UNDER_2G3G, false );
        //
        //        if( downloadPicUnder2G3G || NetworkState.isWifiAvailable( getApplicationContext() ) )
        //        {

        //            new DownloadPicTask( this, iv ).execute( o.file_url );
        ImageLoader.getInstance( HotsActivity.this ).loadImage( o.file_url, iv );
        imageMap.put( o.file_url, iv );

        //        }

        //        byte[] temp = null;
        //        if( ( temp = DataProvider.getInstance( HotsActivity.this ).tryGetTempPic( o.id ) ) != null )
        //        {
        //            // reuse pic from database
        //            try
        //            {
        //                Bitmap tempBitmap = BitmapFactory.decodeByteArray( temp, 0, temp.length );
        //                WeakReference<Bitmap> wrBitmap = new WeakReference<Bitmap>( tempBitmap );
        //                iv.setImageBitmap( wrBitmap.get() );
        //                tempBitmap = null;
        //            }
        //            catch( OutOfMemoryError e )
        //            {
        //                Log.e( "HotsActivity", e.getMessage() );
        //            }
        //
        //        }
        //        else
        //        {
        //            boolean downloadPicUnder2G3G = getSharedPreferences( "setting", Context.MODE_PRIVATE ).getBoolean(
        //                SharedPrefConst.SHARED_PREF_BOOL_DONW_PIC_UNDER_2G3G, false );
        //
        //            if( downloadPicUnder2G3G || NetworkState.isWifiAvailable( getApplicationContext() ) )
        //            {
        //                downloadImage( iv, o.file_url, o.id );
        //            }
        //        }

        // downloadImage(iv, testLink);

        tv.setOnTouchListener( commonTouchListener );
        tv.setOnClickListener( dummyClickListener );
        iv.setOnTouchListener( commonTouchListener );
        iv.setOnClickListener( new OnClickListener()
        {
            public void onClick( View v )
            {
                // TODO go to vendor info with id
                if( !shouldPerformClick )
                    return;
                l( "clicked " + o.id );
                toVendorDetail( o.id );
            }
        } );
    }

    //    private void bindData()
    //    {
    //        bindFood();
    //        bindEntertain();
    //        bindShop();
    //        bindLife();
    //        bindTravel();
    //        show( nowIndex );
    //    }

    //    ArrayList<Object[]> trashBin = new ArrayList<Object[]>();

    private void downloadImage( final ImageView v, final String urlString, final int id )
    {
        new Thread()
        {
            public void run()
            {
                try
                {
                    URL url = new URL( urlString );
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setDoInput( true );
                    conn.connect();
                    InputStream in = conn.getInputStream();

                    l( "before " + in.available() );
                    Bitmap tempBitmap = BitmapFactory.decodeStream( in );

                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    tempBitmap.compress( CompressFormat.JPEG, 30, out );

                    tempBitmap.recycle();
                    tempBitmap = null;

                    // Save the bitmap
                    DataProvider.getInstance( HotsActivity.this ).insertTempPic( id, out.toByteArray() );

                    // SoftReference<Bitmap> s = new
                    // SoftReference<Bitmap>(BitmapFactory.decodeByteArray(out.toByteArray(),
                    // 0, out.toByteArray().length));

                    Bitmap newBitmap = BitmapFactory.decodeByteArray( out.toByteArray(), 0, out.toByteArray().length );
                    l( " -compressed " + out.toByteArray().length );
                    out.close();
                    Object[] objs = { v, newBitmap };
                    mHandler.obtainMessage( MSG_DOWNLOAD_IMAGE_DONE, objs ).sendToTarget();
                    newBitmap = null;
                    in.close();
                    in = null;
                    System.gc();
                }
                catch( Exception e )
                {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    private void fetch()
    {
        fetchThread.start();
        progressBar1.setVisibility( View.VISIBLE );
        ivRightBtn.setEnabled( false );
    }

    private void fetchPost()
    {
        fetchPostThread.start();
        progressBar1.setVisibility( View.VISIBLE );
        ivRightBtn.setEnabled( false );
    }

    View[] vs = new View[5];

    int nowIndex = 0;
    int nowPostIndex = 0;

    private void switchViewClass()
    {
        if( STATE == STATE_PICS )
        {
            if( yFLYING == 1 )
            {
                nowIndex--;
            }
            else
            {
                nowIndex++;
            }
            nowIndex = ( nowIndex + 5 ) % 5;
            l( "switch yFLYING" + yFLYING + ", index" + nowIndex );
            show( nowIndex );
        }
        else
        {
            if( yFLYING == 1 )
            {
                nowPostIndex--;
            }
            else
            {
                nowPostIndex++;
            }
            nowPostIndex = ( nowPostIndex + mPdata.count ) % mPdata.count;
            l( "switch yFLYING" + yFLYING + ",(post) index" + nowIndex );
            showPost( nowPostIndex );
        }
    }

    private void showPost( int index )
    {

        //        for( int i = 0; i < trashBin.size(); i++ )
        //        {
        //            Object[] objs = trashBin.get( i );
        //            ( (ImageView) objs[0] ).setImageResource( R.drawable.member_pic );
        //            ( (Bitmap) objs[1] ).recycle();
        //        }

        l( "p count " + mPdata.pCount );
        final PostsVendor obj = mPdata.data.get( index );

        textRate.setText( (int) ( obj.max_customer_rate * 100 ) + "%" );
        textName.setText( obj.name );
        textAvgPrice.setText( "人均:￥" + (int) obj.average_price );
        //        textDistance.setText( "距离:" + Utils.doDistance( obj.distance ) );
        Log.d( "HotsActivity", "distance: " + obj.distance );
        textDistance.setText( "距离:" + getDistance( obj.lati, obj.longt ) );

        textTag.setText( "" );
        textSubCat.setText( "" );
        textBusinessCir.setText( "" );

        View[] views = new View[] { textTag, textSubCat, textBusinessCir };
        int j = 0;
        for( int i = 0; i < obj.merchant_tags.size(); i++ )
        {
            if( obj.merchant_tags.get( i ).type.equals( "business" ) )
            {
                ( (TextView) views[j] ).setText( obj.merchant_tags.get( i ).name );
                j++;
            }
        }

        textFooterPostMsg.setText( ( index + 1 ) + "/" + mPdata.count );

        //        boolean downloadPicUnder2G3G = getSharedPreferences( "setting", Context.MODE_PRIVATE ).getBoolean(
        //            SharedPrefConst.SHARED_PREF_BOOL_DONW_PIC_UNDER_2G3G, false );
        //
        //        if( downloadPicUnder2G3G || NetworkState.isWifiAvailable( getApplicationContext() ) )
        //        {
        //            //            new DownloadPicTask( this, imagePostCener ).execute( obj.file_url );
        ImageLoader.getInstance( HotsActivity.this ).loadImage( obj.file_url, imagePostCener );
        imageMap.put( obj.file_url, imagePostCener );
        //        }

        //        byte[] temp = null;
        //        if( ( temp = DataProvider.getInstance( HotsActivity.this ).tryGetTempPic( obj.id ) ) != null )
        //        {
        //            // reuse pic from database
        //            Bitmap tempBitmap = BitmapFactory.decodeByteArray( temp, 0, temp.length );
        //            imagePostCener.setImageBitmap( tempBitmap );
        //        }
        //        else
        //        {
        //            boolean downloadPicUnder2G3G = getSharedPreferences( "setting", Context.MODE_PRIVATE ).getBoolean(
        //                SharedPrefConst.SHARED_PREF_BOOL_DONW_PIC_UNDER_2G3G, false );
        //
        //            if( downloadPicUnder2G3G || NetworkState.isWifiAvailable( getApplicationContext() ) )
        //            {
        //                downloadImage( imagePostCener, obj.file_url, obj.id );
        //            }
        //        }

        imagePostCener.setOnClickListener( new OnClickListener()
        {
            public void onClick( View v )
            {
                // TODO with the id (obj.id)
                if( !shouldPerformClick )
                    return;
                l( "post clicked " + obj.id );
                toVendorDetail( obj.id );
            }
        } );
    }

    private String getDistance( String x, String y )
    {
        String strDistance = "0m";

        BDLocation mLoc = Locator.getInstance( null ).getLocation();

        if( FormatConverter.isNotEmptyString( x ) && FormatConverter.isNotEmptyString( y ) && mLoc != null )
        {

            float[] results = new float[1];
            Location.distanceBetween( mLoc.getLatitude(), mLoc.getLongitude(), FormatConverter.toDouble( x ),
                FormatConverter.toDouble( y ), results );
            strDistance = Utils.doDistance( (int) results[0] );
        }
        return strDistance;
    }

    private void show( int index )
    {
        linearFood.setVisibility( View.GONE );
        linearEntertain.setVisibility( View.GONE );
        linearShop.setVisibility( View.GONE );
        linearLife.setVisibility( View.GONE );
        linearTravel.setVisibility( View.GONE );

        //        for( int i = 0; i < trashBin.size(); i++ )
        //        {
        //            Object[] objs = trashBin.get( i );
        //            ( (ImageView) objs[0] ).setImageResource( R.drawable.member_pic );
        //            ( (Bitmap) objs[1] ).recycle();
        //        }
        //        trashBin.clear();

        switch( index )
        {
            case 0:
                bindFood();
                break;
            case 1:
                bindEntertain();
                break;
            case 2:
                bindShop();
                break;
            case 3:
                bindLife();
                break;
            case 4:
                bindTravel();
                break;
        }
        textFooterMsg.setText( ( index + 1 ) + "/5" );
        vs[index].setVisibility( View.VISIBLE );
    }

    int yFLYING = 0;
    boolean shouldPerformClick = true;

    View.OnClickListener dummyClickListener = new OnClickListener()
    {
        public void onClick( View v )
        {
            // do nothing
        }
    };

    View.OnTouchListener commonTouchListener = new OnTouchListener()
    {
        public boolean onTouch( View v, MotionEvent event )
        {
            if( event.getAction() == MotionEvent.ACTION_DOWN )
            {
                shouldPerformClick = true;
            }
            //            else if( event.getAction() == MotionEvent.ACTION_MOVE )
            //            {
            //                shouldPerformClick = false;
            //            }

            detector.onTouchEvent( event );

            //            
            //                        if( event.getAction() == MotionEvent.ACTION_UP )
            //                        {
            //                            if( yFLYING != 0 )
            //                            {
            //                                l( "y flying!" );
            //                                shouldPerformClick = false;
            //                                switchViewClass();
            //                            }
            //                            yFLYING = 0;
            //                        }
            return false;
        }
    };

    GestureDetector detector = new GestureDetector( new OnGestureListener()
    {
        public boolean onSingleTapUp( MotionEvent e )
        {
            return false;
        }

        public void onShowPress( MotionEvent e )
        {

        }

        public boolean onScroll( MotionEvent e1, MotionEvent e2, float distanceX, float distanceY )
        {
            return false;
        }

        public void onLongPress( MotionEvent e )
        {

        }

        private static final int SWIPE_MIN_DISTANCE = 120;
        private static final int SWIPE_THRESHOLD_VELOCITY = 200;

        public boolean onFling( MotionEvent e1, MotionEvent e2, float velocityX, float velocityY )
        {

            Log.i( "Fling", "Fling Happened!" );
            boolean isConsumed = false;

            if( Math.abs( velocityY ) > SWIPE_THRESHOLD_VELOCITY )
            {
                Log.d( "HotsActivity", "velocity is valid!" );
                shouldPerformClick = false;
                if( STATE == STATE_PICS )
                {
                    if( e1.getY() - e2.getY() > SWIPE_MIN_DISTANCE )
                    {
                        HotsActivity.this.vfRecomm.setInAnimation( AnimationUtils.loadAnimation( HotsActivity.this,
                            R.anim.push_top_in ) );
                        HotsActivity.this.vfRecomm.setOutAnimation( AnimationUtils.loadAnimation( HotsActivity.this,
                            R.anim.push_top_out ) );
                        HotsActivity.this.vfRecomm.showNext();
                        if( ++recommPage > 5 )
                        {
                            recommPage = 1;
                        }
                        textFooterMsg.setText( recommPage + "/5" );
                        isConsumed = true;
                    }
                    else if( e1.getY() - e2.getY() < -SWIPE_MIN_DISTANCE )
                    {
                        HotsActivity.this.vfRecomm.setInAnimation( AnimationUtils.loadAnimation( HotsActivity.this,
                            R.anim.push_bottom_in ) );
                        HotsActivity.this.vfRecomm.setOutAnimation( AnimationUtils.loadAnimation( HotsActivity.this,
                            R.anim.push_bottom_out ) );
                        HotsActivity.this.vfRecomm.showPrevious();
                        if( --recommPage == 0 )
                        {
                            recommPage = 5;
                        }
                        textFooterMsg.setText( recommPage + "/5" );
                        isConsumed = true;
                    }
                }
                else
                {

                    if( e1.getY() - e2.getY() > SWIPE_MIN_DISTANCE )
                    {
                        HotsActivity.this.vfPoster.setInAnimation( AnimationUtils.loadAnimation( HotsActivity.this,
                            R.anim.push_top_in ) );
                        HotsActivity.this.vfPoster.setOutAnimation( AnimationUtils.loadAnimation( HotsActivity.this,
                            R.anim.push_top_out ) );
                        HotsActivity.this.vfPoster.showNext();
                        if( ++posterPage > mPdata.data.size() )
                        {
                            posterPage = 1;
                        }
                        textFooterPostMsg.setText( posterPage + "/" + mPdata.data.size() );
                        isConsumed = true;
                    }
                    else if( e1.getY() - e2.getY() < -SWIPE_MIN_DISTANCE )
                    {
                        HotsActivity.this.vfPoster.setInAnimation( AnimationUtils.loadAnimation( HotsActivity.this,
                            R.anim.push_bottom_in ) );
                        HotsActivity.this.vfPoster.setOutAnimation( AnimationUtils.loadAnimation( HotsActivity.this,
                            R.anim.push_bottom_out ) );
                        HotsActivity.this.vfPoster.showPrevious();
                        if( --posterPage == 0 )
                        {
                            posterPage = mPdata.data.size();
                        }
                        textFooterPostMsg.setText( posterPage + "/" + mPdata.data.size() );
                        isConsumed = true;
                    }
                }
            }
            Log.d( "HotsActivity", "fling has been consumed" );

            shouldPerformClick = !isConsumed;
            return isConsumed;
        }

        public boolean onDown( MotionEvent e )
        {
            return false;
        }
    } );

    private void setText( TextView v, String s )
    {
        if( s.length() > 7 )
            s = s.substring( 0, 7 );
        v.setText( s );
    }

    private void l( String s )
    {
        android.util.Log.d( "test", s );
    }

    public void navigationBar( View view )
    {
        //        MainActivity parent = (MainActivity) getParent();
        MainActivityGroup parent = (MainActivityGroup) getParent();
        parent.handleNaviBar();
    }

    public void toVendorDetail( int vendorID )
    {
        Intent intent = new Intent( this, VendorDetailActivity.class );
        intent.putExtra( VendorDetailActivity.EXTRA_INT_MERCHANT_ID, vendorID );
        startActivity( intent );
    }

    //    @Override
    //    public boolean dispatchTouchEvent( MotionEvent event )
    //    {
    //        Log.d( "HotsActivity", "dispatchTouchEvent" );
    //        if( detector.onTouchEvent( event ) )
    //        {
    //            Log.d( "HotsActivity", "detector.onTouchEvent" );
    //            event.setAction( MotionEvent.ACTION_CANCEL );
    //        }
    //        return super.dispatchTouchEvent( event );
    //    }

    //    @Override
    //    public boolean onDown( MotionEvent e )
    //    {
    //        Log.d( "HotsActivity", "onDown()" );
    //        return true;
    //    }
    //
    //    @Override
    //    public void onShowPress( MotionEvent e )
    //    {
    //
    //    }
    //
    //    @Override
    //    public boolean onSingleTapUp( MotionEvent e )
    //    {
    //        return false;
    //    }
    //
    //    @Override
    //    public boolean onScroll( MotionEvent e1, MotionEvent e2, float distanceX, float distanceY )
    //    {
    //        return false;
    //    }
    //
    //    @Override
    //    public void onLongPress( MotionEvent e )
    //    {
    //
    //    }
    //
    //    @Override
    //    public boolean onTouchEvent( MotionEvent event )
    //    {
    //        switch( event.getAction() )
    //        {
    //            case MotionEvent.ACTION_DOWN:
    //                shouldPerformClick = true;
    //                break;
    //            case MotionEvent.ACTION_MOVE:
    //                shouldPerformClick = false;
    //                break;
    //
    //            default:
    //                break;
    //        }
    //        detector.onTouchEvent( event );
    //        Log.d( "HotsActivity", "onTouchEvent()" );
    //        return false;
    //    }
    //
    //    @Override
    //    public boolean onFling( MotionEvent e1, MotionEvent e2, float velocityX, float velocityY )
    //    {
    //        Log.i( "Fling", "Fling Happened!" );
    //        if( STATE == STATE_PICS )
    //        {
    //            if( e1.getY() - e2.getY() > 5 )
    //            {
    //                this.vfRecomm.setInAnimation( AnimationUtils.loadAnimation( this, R.anim.push_top_in ) );
    //                this.vfRecomm.setOutAnimation( AnimationUtils.loadAnimation( this, R.anim.push_top_out ) );
    //                this.vfRecomm.showNext();
    //                if( ++recommPage > 5 )
    //                {
    //                    recommPage = 1;
    //                }
    //                textFooterMsg.setText( recommPage + "/5" );
    //                return true;
    //            }
    //            else if( e1.getY() - e2.getY() < -5 )
    //            {
    //                this.vfRecomm.setInAnimation( AnimationUtils.loadAnimation( this, R.anim.push_bottom_in ) );
    //                this.vfRecomm.setOutAnimation( AnimationUtils.loadAnimation( this, R.anim.push_bottom_out ) );
    //                this.vfRecomm.showPrevious();
    //                if( --recommPage == 0 )
    //                {
    //                    recommPage = 5;
    //                }
    //                textFooterMsg.setText( recommPage + "/5" );
    //                return true;
    //            }
    //            return false;
    //        }
    //        else
    //        {
    //
    //            if( e1.getY() - e2.getY() > 5 )
    //            {
    //                this.vfPoster.setInAnimation( AnimationUtils.loadAnimation( this, R.anim.push_top_in ) );
    //                this.vfPoster.setOutAnimation( AnimationUtils.loadAnimation( this, R.anim.push_top_out ) );
    //                this.vfPoster.showNext();
    //                if( ++posterPage > mPdata.data.size() )
    //                {
    //                    posterPage = 1;
    //                }
    //                textFooterPostMsg.setText( recommPage + "/" + mPdata.data.size() );
    //                return true;
    //            }
    //            else if( e1.getY() - e2.getY() < -5 )
    //            {
    //                this.vfPoster.setInAnimation( AnimationUtils.loadAnimation( this, R.anim.push_bottom_in ) );
    //                this.vfPoster.setOutAnimation( AnimationUtils.loadAnimation( this, R.anim.push_bottom_out ) );
    //                this.vfPoster.showPrevious();
    //                if( --posterPage == 0 )
    //                {
    //                    posterPage = mPdata.data.size();
    //                }
    //                textFooterPostMsg.setText( recommPage + "/" + mPdata.data.size() + "/5" );
    //                return true;
    //            }
    //            return false;
    //        }
    //    }

}
